﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace FileSharing
{
    public class Piece
    {
        private SHA1 sha = new SHA1CryptoServiceProvider();
        
        int ID;
        byte[] Data;

        public int SequenceNumber { get { return ID; } }

        public Piece(int length, int sequenceNumber)
        {
            Data = new byte[length];
            ID = sequenceNumber;
        }

        public Piece(byte[] data, int sequence)
        {
            Data = data;
            ID = sequence;
        }

        public int ChunkCount()
        {
            return (int)Math.Ceiling((double)Data.Length / LocalFile.ChunkSize);
        }

        public byte[] GetChunk(int id)
        {
            int size = Math.Min(Data.Length - LocalFile.ChunkSize * id, LocalFile.ChunkSize);
            byte[] chunk = new byte[size];

            Array.Copy(Data, LocalFile.ChunkSize * id, chunk, 0, size);

            return chunk;
        }

        public void WriteChunk(byte[] chunk, int id)
        {
            Array.Copy(chunk, 0, Data, LocalFile.ChunkSize * id, chunk.Length);
        }

        public bool CheckHash(byte[] hash)
        {
            byte[] DataHash = sha.ComputeHash(Data);

            for (int i = 0; i < hash.Length; i++)
            {
                if (DataHash[i] != hash[i])
                    return false;
            }

            return true;
        }

        public byte[] GetHash()
        {
            return sha.ComputeHash(Data);
        }

        public byte[] GetData()
        {
            return Data;
        }
    }
}
